﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace WH.NurseSys.Report
{
    public partial class ConfigForm : Form
    {
        public ConfigForm()
        {
            InitializeComponent();
            textBoxDBName.Text = ConfigurationManager.AppSettings["database"];
            textBoxDBPwd.Text = ConfigurationManager.AppSettings["dbpwd"];
            textBoxDBUsername.Text = ConfigurationManager.AppSettings["dbuser"];
            textBoxServer.Text = ConfigurationManager.AppSettings["server"];
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //保存
        private void buttonOK_Click(object sender, EventArgs e)
        {
            string server = textBoxServer.Text;
            string dbName = textBoxDBName.Text;
            string dbUser = textBoxDBUsername.Text;
            string dbPwd = textBoxDBPwd.Text;
            string connStr = string.Format("Server={0};Database={1};User Id={2};Password={3};",server, dbName, dbUser, dbPwd);
            ConfigHelper.SetConnectionStr("nurse", connStr);
            this.Close();
        }

        //测试数据库连接
        private void buttonTestConnection_Click(object sender, EventArgs e)
        {
            string server = textBoxServer.Text;
            string dbName = textBoxDBName.Text;
            string dbUser = textBoxDBUsername.Text;
            string dbPwd = textBoxDBPwd.Text;
            if (string.IsNullOrEmpty(server) || string.IsNullOrEmpty(dbName) || string.IsNullOrEmpty(dbUser) || string.IsNullOrEmpty(dbPwd))
            {
                MessageBox.Show("数据库连接信息不全，连接失败");
            }
            string[] values = new string[] { server, dbName, dbUser, dbPwd };
            buttonTestConnection.Enabled = false;
            labelTestMsg.Text = "正在测试连接";
            backgroundWorkerTestConnection.RunWorkerAsync(values);            
        }

        private void backgroundWorkerTestConnection_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] values = e.Argument as string[];
            string connStr = string.Format("Server={0};Database={1};User Id={2};Password={3};", values[0], values[1], values[2], values[3]);
            SqlConnection sqlConn = new SqlConnection(connStr);
            try
            {
                sqlConn.Open();
                sqlConn.Close();
                e.Result = "连接成功";
            }
            catch (Exception ex)
            {
                e.Result = "连接失败,"+ex.Message;
            }
        }

        private void backgroundWorkerTestConnection_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            buttonTestConnection.Enabled = true;
            labelTestMsg.Text = e.Result.ToString();
        }
    }
}
